package com.ithl.eduservice.controller.front;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ithl.commonutils.utils.JwtUtils;
import com.ithl.commonutils.R;
import com.ithl.commonutils.orderVo.CourseDetailInfoOrder;
import com.ithl.eduservice.client.OrderClient;
import com.ithl.eduservice.entity.EduCourse;
import com.ithl.eduservice.entity.chapter.ChapterVo;
import com.ithl.eduservice.entity.frontvo.CourseDetailInfoVo;
import com.ithl.eduservice.entity.frontvo.CourseFrontVo;
import com.ithl.eduservice.service.EduChapterService;
import com.ithl.eduservice.service.EduCourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author hl
 * @Data 2020/4/25
 */
@RestController
@RequestMapping("/eduservice/coursefront")
//@CrossOrigin
public class CourseFrontController {
    @Autowired
    private EduCourseService courseService;
    @Autowired
    private EduChapterService chapterService;
    @Autowired
    private OrderClient orderClient;

    // 课程的条件查询带分页
    @PostMapping("/getCoursePage/{page}/{limit}")
    public R getCoursePage(@PathVariable("page") long page, @PathVariable("limit") long limit,
                           @RequestBody(required = false) CourseFrontVo courseFrontVo) {
        Page<EduCourse> coursePage = new Page<>(page, limit);
        Map<String, Object> map = courseService.getCourseFront(coursePage, courseFrontVo);
        return R.ok().data(map);
    }

    // 课程详情页
    @GetMapping("/getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request) {
        CourseDetailInfoVo courseDetailInfoVo = courseService.getBaseCourseInfo(courseId);
        List<ChapterVo> chapterVideoList = chapterService.getChapterVideo(courseId);
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        boolean isBuy = orderClient.isBuyCourse(courseId, memberId);
        return R.ok().data("chapterVideoList", chapterVideoList).data("courseInfo", courseDetailInfoVo).data("isBuy", isBuy);
    }

    // 根据课程id查询课程信息
    @GetMapping("/getCourseInfoOrder")
    public CourseDetailInfoOrder getCourseInfoOrder(@RequestParam("courseId") String courseId) {
        CourseDetailInfoVo detailInfoVo = courseService.getBaseCourseInfo(courseId);
        CourseDetailInfoOrder detailInfoOrder = new CourseDetailInfoOrder();
        if (detailInfoVo != null) {
            BeanUtils.copyProperties(detailInfoVo, detailInfoOrder);
        }
        return detailInfoOrder;
    }
}
